package vn.ikame.android.truyenf17;

import java.io.IOException;

import vn.ikame.android.handler.CHandler;
import vn.ikame.android.handler.Constants;
import vn.ikame.android.truyenf17voz.R;
import vn.ikame.android.utils.CommonUtils;
import vn.ikame.android.utils.XMLParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class Content extends Activity {
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	String content;
	private AdView adView;
	
	
	//download
	private AlertDialog.Builder alert;
	private ProgressDialog mProgressDialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.content);
		
		if(CHandler.isVozTheme){
			((LinearLayout)findViewById(R.id.mainlayout)).setBackgroundResource(R.drawable.bgvoz);
		} else {
			((LinearLayout)findViewById(R.id.mainlayout)).setBackgroundResource(R.drawable.storylist);
		}
		
		LinearLayout lLinLayout = (LinearLayout) findViewById(R.id.layoutcontent);
	    
	    RelativeLayout.LayoutParams adParams2 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams2.addRule(RelativeLayout.ALIGN_BOTTOM);
		adParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
		
		
		adView = new AdView(this, AdSize.SMART_BANNER, "a1502465d6a93ed");
		adView.loadAd(new AdRequest());

		lLinLayout.addView(adView, adParams2);

			if(CommonUtils.isNetworkConnected(this)){
				((TextView)findViewById(R.id.chap_title)).setText(CHandler.storyName + "\n" + CHandler.chapName);
				
				showDialog(DIALOG_DOWNLOAD_PROGRESS);
				
				WebView wv = (WebView) findViewById(R.id.webview);
				wv.setBackgroundColor(Color.TRANSPARENT);
				wv.setBackgroundDrawable(null);
				wv.setBackgroundResource(0);
				wv.loadUrl("http://data.ikame.vn/f17/index.php?sid=" + CHandler.chapID);
				
				WebView wv2 = (WebView) findViewById(R.id.viewads);
				wv2.setBackgroundColor(Color.TRANSPARENT);
				wv2.setBackgroundDrawable(null);
				wv2.setBackgroundResource(0);
				wv2.loadUrl(Constants.DATA_LINK + "index.php?sid=1167");
				
				wv.setWebViewClient(new WebViewClient() {

					   public void onPageFinished(WebView view, String url) {
						   try{
							   dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
						   }catch (Exception e) {
							// TODO: handle exception
						   }
						   
						   if(CHandler.chapPos < CHandler.chapList.size() - 1){
								TextView next = (TextView) findViewById(R.id.next_chap);
								next.setText("\nCHAP KẾ TIẾP");
								next.setOnClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										CHandler.chapPos++;
										CHandler.chapName = CHandler.chapList.get(CHandler.chapPos).getChapName();
										CHandler.chapID = CHandler.chapList.get(CHandler.chapPos).getId();
										Content.this.finish();
										Content.this.startActivity(new Intent(Content.this, Content.class));
									}
								});
							}
					    }
					});
				
				
				
				try{
					StoryList.detailsTracker.trackPageView("ReadChap_" + CHandler.storyName + " - " + CHandler.chapName);
					StoryList.detailsTracker.dispatch();
				}catch (Exception e) {
					// TODO: handle exception
				}
				
	        } else {
	        	alert = new AlertDialog.Builder(this);
	        	alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
	    		alert.setPositiveButton("Thoát chương trình",
	    				new DialogInterface.OnClickListener() {
	    					public void onClick(DialogInterface dialog,
	    							int whichButton) {
	    						Content.this.finish();
	    						System.gc();
	    						android.os.Process.killProcess(android.os.Process.myPid());
	    					}
	    				});
	    		alert.setNegativeButton("Đóng",
	    				new DialogInterface.OnClickListener() {
	    					public void onClick(DialogInterface dialog,
	    							int whichButton) {
	    					}
	    				});
	    		
	    		alert.setCancelable(false);
	    		alert.show();
	        }
		
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu_content, menu);
	    return true;
	}
	
	public void createAboutMessage(){
		alert = new AlertDialog.Builder(this);
		alert.setMessage(R.string.about);
		alert.setPositiveButton("Gửi mail",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

						/* Fill it with Data */
						emailIntent.setType("plain/text");
						emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"support@ikame.vn"});
						emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Ứng dụng truyện ngắn - f145");
						emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Nội dung: ");

						/* Send it off to the Activity-Chooser */
						startActivity(Intent.createChooser(emailIntent, "Send mail..."));
					}
				});

		alert.setNegativeButton("Đóng",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
					}
				});
		alert.setCancelable(false);
		alert.show();
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
//		case R.id.change:
//			CHandler.isVozTheme = !CHandler.isVozTheme;
//			CHandler.store.setVozTheme(!CHandler.isVozTheme);
//			if(CHandler.isVozTheme){
//				((LinearLayout)findViewById(R.id.mainlayout)).setBackgroundResource(R.drawable.bgvoz);
//			} else {
//				((LinearLayout)findViewById(R.id.mainlayout)).setBackgroundResource(R.drawable.storylist);
//			}
//			break;
		case R.id.mark:
			CHandler.store.setChapID(CHandler.chapID);
			CHandler.store.setStoryID(CHandler.storyID);
			CHandler.store.setChapPos(CHandler.chapPos);
			CHandler.store.setStoryName(CHandler.storyName);
			Toast.makeText(this, "Đánh dấu truyện thành công ", Toast.LENGTH_SHORT).show();
			break;
		case R.id.refresh:
			if(CommonUtils.isNetworkConnected(this)){
				((TextView)findViewById(R.id.chap_title)).setText(CHandler.storyName + "\n" + CHandler.chapName);
				
				showDialog(DIALOG_DOWNLOAD_PROGRESS);
				
				WebView wv = (WebView) findViewById(R.id.webview);
				wv.setBackgroundColor(Color.TRANSPARENT);
				wv.setBackgroundDrawable(null);
				wv.setBackgroundResource(0);
				wv.loadUrl("http://data.ikame.vn/f17/index.php?sid=" + CHandler.chapID);
				
				wv.setWebViewClient(new WebViewClient() {

					   public void onPageFinished(WebView view, String url) {
						   
						   try{
							   dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
						   }catch (Exception e) {
							// TODO: handle exception
						   }	
						   
						   if(CHandler.chapPos < CHandler.chapList.size() - 1){
								TextView next = (TextView) findViewById(R.id.next_chap);
								next.setText("CHAP KẾ TIẾP");
								next.setOnClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										CHandler.chapPos++;
										CHandler.chapName = CHandler.chapList.get(CHandler.chapPos).getChapName();
										CHandler.chapID = CHandler.chapList.get(CHandler.chapPos).getId();
										Content.this.finish();
										Content.this.startActivity(new Intent(Content.this, Content.class));
									}
								});
							}
					    }
					});
				
	        } else {
	        	alert = new AlertDialog.Builder(this);
	        	alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
	    		alert.setPositiveButton("Thoát chương trình",
	    				new DialogInterface.OnClickListener() {
	    					public void onClick(DialogInterface dialog,
	    							int whichButton) {
	    						Content.this.finish();
	    						System.gc();
	    						android.os.Process.killProcess(android.os.Process.myPid());
	    					}
	    				});
	    		alert.setNegativeButton("Đóng",
	    				new DialogInterface.OnClickListener() {
	    					public void onClick(DialogInterface dialog,
	    							int whichButton) {
	    					}
	    				});
	    		
	    		alert.setCancelable(false);
	    		alert.show();
	        }
			break;
		case R.id.about:
			createAboutMessage();
			break;

		}
		return true;
	}
	
	
	public void initChapContent(){
		try {
			//Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					//Hiển thị thông báo
					showDialog(DIALOG_DOWNLOAD_PROGRESS);
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {
						content = XMLParser.getcontent("http://data.ikame.vn/f17/index.php?sid=" + CHandler.chapID);
						System.out.println("chapID = " + CHandler.chapID);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return "";
				}
				//Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {
					
					
					try{
					   dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
				    }catch (Exception e) {
					// TODO: handle exception
				    }
					
				}
			}.execute();
		} catch (Exception e) {
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(CHandler.isReadMarkChap){
				this.finish();
				startActivity(new Intent(Content.this, ChapList.class));
				return true;
			} else {
				this.finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
	
	
}

